<template>
  <view class="login-container">
    <!-- 头部Logo -->
    <view class="logo-container">
      <text class="logo-text">校园失物招领</text>
    </view>

    <!-- 登录表单 -->
    <view class="form-container">
      <!-- 学号输入 - 使用头像图标 -->
      <view class="input-group">
        <uni-icons type="person" size="24" color="#999" class="input-icon"></uni-icons>
        <input
            type="text"
            placeholder="请输入学号"
            class="input-field"
            v-model="userId"
            @focus="handleFocus('userId')"
            @blur="handleBlur('userId')"
            :class="{ 'error-border': userIdError }"
        />
      </view>
      <text class="error-msg" v-if="userIdError">{{userIdError}}</text>

      <!-- 密码输入 -->
      <view class="input-group">
        <uni-icons type="locked" size="24" color="#999" class="input-icon"></uni-icons>
        <input
            type="password"
            placeholder="请输入密码"
            class="input-field"
            v-model="password"
            @focus="handleFocus('password')"
            @blur="handleBlur('password')"
            :class="{ 'error-border': passwordError }"
        />
      </view>
      <text class="error-msg" v-if="passwordError">{{passwordError}}</text>

      <!-- 辅助功能区 -->
      <view class="helper-container">
        <view class="remember-me">
          <checkbox-group @change="toggleRemember">
            <checkbox :checked="rememberMe" color="#4A90E2" />
            <text>记住密码</text>
          </checkbox-group>
        </view>
        <view class="forgot-password" @click="handleForgotPassword">
          <text>忘记密码?</text>
        </view>
      </view>

      <!-- 登录按钮 -->
      <button
          class="login-btn"
          :class="{active: isBtnActive, 'btn-loading': isLoading}"
          :loading="isLoading"
          @click="handleLogin"
          @touchstart="handleBtnTouchStart"
          @touchend="handleBtnTouchEnd"
          :disabled="isLoading"
      >
        {{ isLoading ? '登录中...' : '登录' }}
      </button>
    </view>

    <!-- 底部提示 -->
    <view class="footer-tip">
      <text>未注册账号? <text class="register-link" @click="handleRegister">立即注册</text></text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

// 表单数据
const userId = ref('');
const password = ref('');
const rememberMe = ref(false);
const isLoading = ref(false);

// 错误信息
const userIdError = ref('');
const passwordError = ref('');

// 按钮状态
const isBtnActive = ref(false);

// API基础URL
const API_BASE_URL = 'http://172.20.10.2:8080/api';

// 从本地存储获取记住的账号密码
const savedUserId = ref(uni.getStorageSync('savedUserId') || '');
const savedPassword = ref(uni.getStorageSync('savedPassword') || '');
const savedRememberMe = ref(uni.getStorageSync('savedRememberMe') || false);

// 显示提示框
const showToast = (title, icon = 'none', duration = 1500) => {
  uni.showToast({
    title,
    icon,
    duration
  });
};

// 显示加载框
const showLoading = (title = '加载中...') => {
  uni.showLoading({
    title,
    mask: true
  });
};

// 隐藏加载框
const hideLoading = () => {
  uni.hideLoading();
};

// 输入框焦点处理
const handleFocus = (type) => {
  if (type === 'userId') userIdError.value = '';
  if (type === 'password') passwordError.value = '';
};

const handleBlur = (type) => {
  if (type === 'userId') validateUserId();
  if (type === 'password') validatePassword();
};

// 验证学号
const validateUserId = () => {
  if (!userId.value) {
    userIdError.value = '请输入学号';
    return false;
  }
  userIdError.value = '';
  return true;
};

// 验证密码
const validatePassword = () => {
  if (!password.value) {
    passwordError.value = '请输入密码';
    return false;
  }
  if (password.value.length < 6) {
    passwordError.value = '密码长度不能少于6位';
    return false;
  }
  passwordError.value = '';
  return true;
};

// 记住密码切换
const toggleRemember = () => {
  rememberMe.value = !rememberMe.value;
};

// 忘记密码
const handleForgotPassword = () => {
  uni.navigateTo({
    url: '/pages/forgot-password/forgot-password'
  });
};

// 注册新账号
const handleRegister = () => {
  uni.navigateTo({
    url: '/pages/register/register'
  });
};

// 按钮交互效果
const handleBtnTouchStart = () => {
  if (!isLoading.value) {
    isBtnActive.value = true;
  }
};

const handleBtnTouchEnd = () => {
  isBtnActive.value = false;
};

// 登录处理
const handleLogin = async () => {
  // 验证表单
  if (!validateUserId() || !validatePassword()) return;

  showLoading('登录中...');
  isLoading.value = true;

  try {
    // 调用后端登录API
    const response = await uni.request({
      url: `${API_BASE_URL}/login`,
      method: 'GET',
      data: {
        userId: userId.value,
        password: password.value
      }
    });

    // 处理后端响应
    const resData = response.data;
    if (resData.code === 200) {
      // 登录成功
      const data = resData.data;
      if (data.state === 'true') {
        // 存储token和用户信息
        uni.setStorageSync('token', data.token);
        uni.setStorageSync('userId', data.userId);

        // 记住密码逻辑
        if (rememberMe.value) {
          uni.setStorageSync('savedUserId', userId.value);
          uni.setStorageSync('savedPassword', password.value);
          uni.setStorageSync('savedRememberMe', true);
        } else {
          uni.removeStorageSync('savedUserId');
          uni.removeStorageSync('savedPassword');
          uni.setStorageSync('savedRememberMe', false);
        }

        showToast('登录成功', 'success');

        // 延迟跳转至首页
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/mine/mine'
          });
        }, 800);
      } else {
        showToast(data.msg, 'error');
      }
    } else {
      showToast(resData.message || '登录失败，请重试', 'error');
    }
  } catch (error) {
    console.error('登录请求失败', error);
    showToast('网络错误，请检查网络或稍后再试', 'error');
  } finally {
    hideLoading();
    isLoading.value = false;
  }
};

// 页面加载时检查是否有记住的账号密码
onMounted(() => {
  if (savedRememberMe.value && savedUserId.value && savedPassword.value) {
    userId.value = savedUserId.value;
    password.value = savedPassword.value;
    rememberMe.value = savedRememberMe.value;
  }
});
</script>

<style>
page {
  height: 100%;
  background-color: #F5F7FA;
}

.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
  padding: 0 40rpx;
  box-sizing: border-box;
}

.logo-container {
  margin-top: 120rpx;
  margin-bottom: 80rpx;
}

.logo-text {
  font-size: 36px;
  font-weight: bold;
  color: #333;
}

.form-container {
  width: 100%;
  max-width: 600rpx;
}

.input-group {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  padding: 20rpx 24rpx;
  margin-bottom: 24rpx;
  border: 1px solid #E4E7ED;
  transition: all 0.3s;
}

.input-group.error-border {
  border-color: #F56C6C;
}

.input-group:focus-within {
  border-color: #4A90E2;
  box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.2);
}

.input-icon {
  margin-right: 16rpx;
  vertical-align: middle; /* 确保图标垂直居中 */
}

.input-field {
  flex: 1;
  height: 40rpx;
  font-size: 14px;
  color: #333;
}

.error-msg {
  display: block;
  font-size: 12px;
  color: #F56C6C;
  margin-bottom: 8rpx;
  height: 20px;
  line-height: 20px;
}

.helper-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.remember-me {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.forgot-password {
  font-size: 14px;
  color: #4A90E2;
}

.login-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 8px;
  font-size: 16px;
  color: #fff;
  background: linear-gradient(to right, #4A90E2, #357ABD);
  border: none;
  margin: 0;
  transition: all 0.2s;
  box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.25);
}

.login-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.login-btn.btn-loading {
  opacity: 0.8;
  cursor: not-allowed;
}

.login-btn::after {
  border: none;
}

.footer-tip {
  position: absolute;
  bottom: 60rpx;
  font-size: 14px;
  color: #909399;
}

.register-link {
  color: #4A90E2;
  margin-left: 4rpx;
}
</style>